package com.longcai.cm.moudules.system.service.impl;


import cn.hutool.core.util.RandomUtil;
import cn.hutool.crypto.digest.MD5;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.longcai.cm.base.service.BaseServiceImpl;
import com.longcai.cm.exception.SysRuntimeException;
import com.longcai.cm.moudules.system.dao.SysDicCodeMapper;
import com.longcai.cm.moudules.system.dao.SysDicValueMapper;
import com.longcai.cm.moudules.system.domain.SysDicCode;
import com.longcai.cm.moudules.system.domain.SysDicValue;
import com.longcai.cm.moudules.system.service.SysDicCodeService;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.formula.functions.T;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service(value = "SysDicCodeService")
public class SysDicCodeServiceImpl extends BaseServiceImpl<SysDicCode> implements SysDicCodeService {

    private Logger logger = LoggerFactory.getLogger(getClass());

    @Resource
    private SysDicCodeMapper SysDicCodeMapper;

    @Resource
    private SysDicValueMapper sysDicValueMapper;


    @Override
    public String getTextValueByCode(String code) {
        SysDicCode sysDicCode = getDicCode(code);

        LambdaQueryWrapper<SysDicValue> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysDicValue::getDid, sysDicCode.getId());
        SysDicValue sysDicValue = sysDicValueMapper.selectOne(queryWrapper);
        return sysDicValue == null ? "" : sysDicValue.getValue();
    }

    @Override
    public List<String> getListValueByCode(String code) {
        final List<SysDicValue> dicValues = getListByCode(code);
        if (dicValues.size() > 0) {
            return dicValues.stream().map(SysDicValue::getValue).collect(Collectors.toList());
        } else {
            return new ArrayList<>();
        }
    }

    @Override
    public List<SysDicValue> getListByCode(String code) {
        SysDicCode sysDicCode = getDicCode(code);
        LambdaQueryWrapper<SysDicValue> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysDicValue::getDid, sysDicCode.getId());
        queryWrapper.orderByAsc(SysDicValue::getOderNo);
        final List<SysDicValue> values = sysDicValueMapper.selectList(queryWrapper);
        return values.size() > 0 ? values : new ArrayList<>();
    }

    private SysDicCode getDicCode(String code) {
        LambdaQueryWrapper<SysDicCode> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysDicCode::getCode, code);
        final SysDicCode dicCode = SysDicCodeMapper.selectOne(wrapper);
        if (dicCode == null) {
            throw new SysRuntimeException("配置项目缺失，无法运行");
        }
        return dicCode;
    }
}
